<template>
  <div
    id="PostPage"
    v-if="Object.keys(post).length!==0&&!isLoading"
    class="fixed lg:flex justify-between z-50 top-0 left-0 w-full h-full bg-black lg:overflow-hidden overflow-auto"
  >
    <div class="lg:w-[calc(100%-540px)] h-full relative">
      <a
        @click="back"
        href="javascript:;"
        class="absolute z-20 m-5 rounded-full bg-gray-700 p-1.5 hover:bg-gray-800"
      >
        <Icon name="icon-guanbi" color="#FFFFFF" size="27"/>
      </a>

      <div>
        <button
          @click="loopThroughPostsUp()"
          v-throttle="1000"
          class="absolute z-20 right-4 top-4 flex items-center justify-center rounded-full bg-gray-700 p-1.5 hover:bg-gray-800"
        >
          <Icon name="icon-up" size="30" color="#FFFFFF"/>
        </button>

        <button
          @click="loopThroughPostsDown()"
          v-throttle="1000"
          class="absolute z-20 right-4 top-20 flex items-center justify-center rounded-full bg-gray-700 p-1.5 hover:bg-gray-800"
        >
          <Icon name="icon-down" size="30" color="#FFFFFF"/>
        </button>
      </div>

      <img
        class="absolute top-[18px] left-[70px] rounded-full lg:mx-0 mx-auto z-999"
        width="45"
        src="~/assets/images/tiktok-logo-small.png"
      >
      <div v-if="post.video.play_addr.url_list.length!==0&&post.video.play_addr.url_list[0]" class="lg:w-[100%] h-full relative">
        <XgVideo :url="post.video.play_addr.url_list[0]"></XgVideo>
      </div>
      <div
        v-if="!isLoaded"
        class="flex items-center justify-center bg-black bg-opacity-70 h-screen lg:min-w-[480px]"
      >
        <Icon class="animate-spin ml-1" name="icon-load-c" size="100" color="#FFFFFF"/>
      </div>
      <div class="bg-black bg-opacity-70 lg:min-w-[480px]">
      </div>

    </div>
    <div
      id="InfoSection"
      class="lg:max-w-[550px] relative w-full h-full bg-white"
    >

      <div class="py-7"/>

      <div class="flex items-center justify-between px-8">
        <div class="flex items-center">
          <a href="javascript:;">
            <img
              class="rounded-full lg:mx-0 mx-auto"
              width="40"
              :src="post.author.avatar_thumb.url_list[0]"
            >
          </a>
          <div class="ml-3 pt-0.5">
            <div class="text-[17px] font-semibold">
              {{ post.author.nickname }}
            </div>
            <div class="text-[13px] -mt-5 font-light">
              {{ post.author.nickname }}
              <span class="relative -top-[2px] text-[30px] pr-0.5 ">.</span>
              <span class="font-medium">{{ post.create_time|timestampToTime }}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="px-8 mt-4 text-sm">{{ post.desc }}</div>

      <div class="px-8 mt-4 text-sm font-bold">
        <Icon name="icon-yinle" size="17" style="display: inline;"/>
        original sound - {{ post.music ? post.music.author : post.author.nickname }}
      </div>

      <div class="flex items-center px-8 mt-8">
        <div class="pb-4 text-center flex items-center">
          <button
            class="rounded-full bg-gray-200 p-2 cursor-pointer"
          >
            <Icon
              name="icon-yidianzan"
              size="25"
            />
          </button>
          <span class="text-xs pl-2 pr-4 text-gray-800 font-semibold">
               {{ post.statistics.digg_count |million }}
          </span>
        </div>

        <div class="pb-4 text-center flex items-center">
          <div class="rounded-full bg-gray-200 p-2 cursor-pointer">
            <Icon name="icon-pinglun1" size="22"/>
          </div>
          <span
            class="text-xs pl-2 pr-4 text-gray-800 font-semibold">{{ post.statistics.comment_count |million }}</span>
        </div>
        <div class="pb-4 text-center flex items-center">
          <div class="rounded-full bg-gray-200 p-2 cursor-pointer">
            <Icon name="icon-fenxiang" size="22"/>
          </div>
          <span class="text-xs pl-2 text-gray-800 font-semibold">{{ post.statistics.share_count |million }}</span>
        </div>
      </div>
      <div
        id="Comments"
        ref="Comments"
        @scroll="scroll"
        class="bg-[#F8F8F8] z-0 w-full h-[calc(100%-200px)] border-t-2 overflow-auto"
      >

        <div class="pt-2"/>

        <div
          class="text-center mt-6 text-xl text-gray-500"
          v-if="(comments&&comments.length < 1)"
        >
          No comments...
        </div>

        <div
          v-else
          v-for="(comment,index) in comments"
          :key="index"
          class="flex items-center justify-between px-8 mt-4"
        >
          <div class="flex items-center relative w-full">
            <a href="javascript:;">
              <img
                class="absolute top-0 rounded-full lg:mx-0 mx-auto"
                width="40"
                :src="comment.user.avatar_300x300.url_list[0]"
              >
            </a>
            <div class="ml-14 pt-0.5 w-full">
              <div class="text-[18px] font-semibold flex items-center justify-between">
                {{ comment.user.nickname }}
              </div>
              <div class="text-[15px] font-light">
                {{ comment.text }}
              </div>
            </div>
          </div>
        </div>

        <div class="mb-28"/>

      </div>

    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isLoaded: false,
      comment: null,
      inputFocused: false,
      comments: [],
      index: null,
      isLoading: false,
      onFetching: false,
      cursor: 0,
      isLoadAll: false,
      total: 0
    }
  },
  filters: {
    timestampToTime: function (timestamp) {
      let date = new Date(timestamp * 1000);
      let Y = date.getFullYear() + "-";
      let M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      let D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      let h = date.getHours() + ":";
      let m = date.getMinutes() + ":";
      let s = date.getSeconds();
      return Y + M + D + h + m + s;
    },
    million: function (value) {
      let num;
      if (value > 9999) {
        num = (Math.floor(value / 1000) / 10) + '万';
      } else if (value < 9999 && value > -9999) {
        num = value
      } else if (value < -9999) {
        num = -(Math.floor(Math.abs(value) / 1000) / 10) + '万'
      }
      return num;
    }
  },
  watch: {
    '$route.query.id': {
      handler(newVal) {
        if (this.$refs.Comments) {
          this.isLoadAll = false
          this.$refs.Comments.scrollTop = 0
        }
        this.index = newVal
        this.getComment(0)
      }
    },
    index: {
      handler(newVal) {
        if (newVal >= this.length - 3) {
          this.getList()
        }
      }, immediate: true
    },
    length: {
      async handler(newVal) {
        if (newVal === 0) {
          this.isLoading = true;
          await this.getList(true)
        }
      }, immediate: true
    }
  },
  computed: {
    post() {
      return this.$store.state.post.list[this.index] || {}
    },
    length() {
      return this.$store.state.post.list.length
    }
  },
  async mounted() {
    this.index = Number(this.$route.query.id)
    // window.addEventListener("keydown", this.KeyDown, true);
    this.$nextTick(async () => {
      await this.getComment(0)
    })
  },
  async created() {
    this.index = Number(this.$route.query.id)
  },
  methods: {
    KeyDown(e) {
      if (e.keyCode === 40) {
        this.loopThroughPostsDown()
      } else if (e.keyCode === 38) {
        this.loopThroughPostsUp()
      }
    },
    back() {
      this.$router.go(-1)
    },
    scroll() {
      if (this.isLoadAll) return;
      if (!this.onFetching) {
        if (this.$refs.Comments.scrollHeight - this.$refs.Comments.scrollTop - this.$refs.Comments.offsetHeight <= 200) {
          this.onFetching = true;
          setTimeout(() => {
            //调接口获取数据
            this.cursor += 20
            this.getComment(this.cursor, true)
            this.onFetching = false;
          }, 500);
        }
      }
    },
    async getComment(cursor, flag) {
      try {
        let aweme_id = this.$store.state.post.list[this.$route.query.id].aweme_id
        if (this.$store.state.post.list.length === 0 || !aweme_id) return;
        let res = await this.$axios({
          method: 'get',
          withCredentials: false,
          url: `http://127.0.0.1:4500/getComment?aweme_id=${aweme_id}&cursor=${cursor}`,
        })
        this.total = res.data.data.total
        if (flag) {
          if (!res.data.data.comments || res.data.data.comments.length === 0) {
            this.isLoadAll = true;
            return;
          }
          if (res && res.data.data.comments.length !== 0) {
            this.comments.push(...res.data.data.comments)
          }
          return;
        }
        this.comments = res.data.data.comments
      } catch (e) {
        console.log(e)
      }
    },
    async getList(flag) {
      try {
        const res = await this.$axios({
          method: 'get',
          withCredentials: false,
          url: 'http://127.0.0.1:4500/getData'
        })
        this.isLoading = false
        let list = res.data.data.aweme_list
        if (list && list.length) {
          let arr = []
          for (let i = 0; i < list.length; i++) {
            if (list[i].video.bit_rate.length !== 0) {
              arr.push(list[i])
            }
          }
          this.$store.commit('post/addVideo', arr)
          if (flag) {
            console.log(2222)
            await this.$router.replace(`/postSecond?id=${0}`)
          }
        }
      } catch (e) {

      }
    },
    loopThroughPostsUp() {
      try {
        setTimeout(() => {
          let index = this.index - 1
          if (index >= 0) {
            this.$router.replace(`/postSecond?id=${index}`)
          } else {
            this.$router.replace(`/postSecond?id=${this.$store.state.post.list.length - 1}`)
          }
        }, 300)
      } catch (e) {

      }
    },
    loopThroughPostsDown() {
      try {
        setTimeout(() => {
          let index = Number(this.index) + 1
          // if (index === this.$store.state.post.list.length - 1) {
          //   try {
          //     this.getList()
          //   } catch (e) {
          //     this.getList()
          //   }
          // }
          this.$router.replace(`/postSecond?id=${index}`)
        }, 300)
      } catch (e) {

      }
    },
  }
  ,
}
</script>
